<?php

namespace App\Http\Controllers\Backstage;

use App\Http\Models\Backstage\AdminResetPassword;
use App\Http\Models\Backstage\AdminUser;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;

class LoginController extends Controller
{
    use AuthenticatesUsers;



    protected $redirectTo = '/Admin/index.html';

    protected $guard = 'admin';

    //错误次数
    public $maxLoginAttempts = 5;

    function __construct()
    {
        $this->middleware('guest:admin', ['except' => 'logout']);

    }

    /**
     * 登录界面
     * User: 6点
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {

        //输出界面
        $this->title = '后台登录';

        return $this->render('Backstage.Login.index');
    }

    /**
     * 登录接口
     * User: 6点
     * @param Request $request
     */
    public function login(Request $request)
    {

        $fromErr = $this->validatorFrom([
            'account' => 'required|alpha_dash|max:50',
            'password' => 'required|alpha_dash|max:50',
            'logincode'=>'required|alpha_dash|max:6',
        ]);
        if($fromErr){
            return $fromErr;
        }

        $username = Input::get('account') ;
        $password = Input::get('password') ;
        $logincode = Input::get('logincode') ;

        if(\Session::pull('milkcaptcha') != $logincode) {
            return echoErr('验证码错误','600001');
        }

        $adminUser = AdminUser::findWhere(['admin_user_account'=>$username]);

        if(!$adminUser || $adminUser['admin_user_status'] == 2){
            return echoErr('账号不存在或者被禁止使用!');
        }

        if ($lockedOut = $this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return echoErr('错误次数过多，请稍后再试!');
        }

        $r = Auth::guard($this->guard)->attempt(['admin_user_account'=>$username,'password'=>$password]);

        if(!$r){
            if (! $lockedOut) {
                $this->incrementLoginAttempts($request);
            }
            return echoErr('用户密码错误');
        }


        return echoOk();
    }

    protected function guard()
    {

        return Auth::guard($this->guard);
    }



    public function forgotPassMail()
    {
        //输出界面
        $this->title = '找回密码';

        if($_POST){
            $fromErr = $this->validatorFrom([
                'mail'=>'required|email|max:50',
            ]);
            if($fromErr){
                return $fromErr;
            }

            $mail = Input::get('mail');

            $resetRoken = md5(csrf_token().(time()));

            $model = AdminResetPassword::addData($mail,$resetRoken);

            if(!$model){
                return echoErr('发送错误');
            }

            $flag = \Mail::send('Backstage.Login.password',['resetRoken'=>$resetRoken],function($message)use($mail){
                $to = $mail;
                $message ->to($to)->subject('重置密码');
            });

            return echoOk();
        }


        return $this->render('Backstage.Login.forgotPasswordMail');
    }

    public function resetPass(){
        //输出界面
        $this->title = '重置密码';

        $token = Input::get('token');

        if($_POST){
            $fromErr = $this->validatorFrom([
                'pass'=>'required|alpha_dash|max:50',
                'cpass'=>'required|alpha_dash|max:50',
                'token'=>'required|alpha_dash|max:200',
            ]);
            if($fromErr){
                return $fromErr;
            }

            $pass = Input::get('pass');
            $cpass = Input::get('cpass');

            if($pass != $cpass){
                return echoErr('密码不一致');
            }

            $data = AdminResetPassword::findTokenData($token);

            if(!$data){
                return echoErr('修改失败!');
            }
            $user = AdminUser::findEmailData($data['admin_user_email']);

            if(!$user){
                return echoErr('账号不存在!');
            }
            $user->admin_user_password = bcrypt($pass);

            $r = $user->save();

            if(!$r){
                return echoErr('修改失败');
            }

            $data->delete();

            return echoOk();
        }


        return $this->showView('Backstage.Login.resetpass',['token'=>$token]);
    }
}
